<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="bg-decoration"></div>

    <!-- 登录卡片 -->
    <el-card class="login-card" shadow="hover">
      <div class="login-header">
        <h2 class="login-title">系统登录</h2>
        <p class="login-desc">请输入用户名或邮箱登录</p> <!-- 提示文案修改 -->
      </div>

      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          label-position="left"
          label-width="70px"
      >
        <!-- 输入框标签改为「账号」，支持用户名/邮箱 -->
        <el-form-item label="账号" prop="account">
          <el-input
              v-model="loginForm.account"
              placeholder="请输入用户名或邮箱"
          prefix-icon="User"
          :disabled="isLoading"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              :disabled="isLoading"
              show-password
          />
        </el-form-item>

        <el-form-item class="remember-me">
          <el-checkbox v-model="loginForm.remember" :disabled="isLoading">
            记住密码
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              :loading="isLoading"
              @click="handleLogin"
          >
            登录
          </el-button>
          <!-- 注册链接 -->
          <div class="register-link" style="text-align: center; margin-top: 15px;">
            还没有账号？
            <el-link type="primary" @click="openRegisterDialog">立即注册</el-link>
          </div>
        </el-form-item>

        <!-- 注册弹窗 -->
        <el-dialog
            v-model="isRegisterDialogOpen"
            title="用户注册"
            width="600px"
            :close-on-click-modal="false"
            append-to-body
            custom-class="register-dialog"
        >
          <RegisterForm @success="handleRegisterSuccess" @close="isRegisterDialogOpen = false"/>
        </el-dialog>
      </el-form>
    </el-card>

    <!-- 页脚信息 -->
    <footer class="login-footer">
      © 2025-2025 幸福小站. All rights reserved.
    </footer>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';
import {ElForm, ElFormItem, ElInput, ElButton, ElCheckbox, ElCard, ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';
import {useAuthStore} from "../stores/auth.ts";
import RegisterForm from "./RegisterForm.vue";

const authStore = useAuthStore()

// 登录表单类型定义：将 username 改为 account（兼容用户名和邮箱）
interface LoginForm {
  account: string; // 账号：可输入用户名或邮箱
  password: string;
  remember: boolean;
}

// 表单引用
const loginFormRef = ref<InstanceType<typeof ElForm>>();
// 路由实例
const router = useRouter();

// 登录表单数据：username 改为 account
const loginForm = reactive<LoginForm>({
  account: '',
  password: '',
  remember: false
});

// 加载状态
const isLoading = ref<boolean>(false);

// 表单验证规则：放宽 account 验证（支持用户名或邮箱格式）
const loginRules = {
  account: [
    {required: true, message: '请输入用户名或邮箱', trigger: 'blur'},
    {
      validator: (rule: any, value: string, callback: any) => {
        // 正则：支持用户名（3-20位字母/数字/下划线）或邮箱格式
        const accountReg = /^([a-zA-Z0-9_]{3,20}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/;
        if (!accountReg.test(value)) {
          callback(new Error('请输入合法的用户名（3-20位字母/数字/下划线）或邮箱'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 8, message: '密码长度至少 8 个字符', trigger: 'blur'} // 与注册密码规则保持一致
  ]
};

// 处理登录：传递 account 给后端，由后端判断是用户名还是邮箱
const handleLogin = async () => {
  // 表单验证
  if (!loginFormRef.value) return;
  const valid = await loginFormRef.value.validate();

  if (valid) {
    try {
      isLoading.value = true;
      // 调用 authStore.login 时传递 account（而非 username）
      await authStore.login(loginForm.account, loginForm.password);
      await router.push('/');

      // 记住密码：存储 account 而非 username
      if (loginForm.remember) {
        localStorage.setItem('account', loginForm.account);
        localStorage.setItem('password', loginForm.password);
      } else {
        localStorage.removeItem('account');
        localStorage.removeItem('password');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '登录失败，请检查账号或密码');
      console.error('Login error:', error);
    } finally {
      isLoading.value = false;
    }
  }
};

// 初始化 - 读取记住的账号（从 account 字段读取，兼容旧数据）
onMounted(() => {
  const savedAccount = localStorage.getItem('account') || localStorage.getItem('username'); // 兼容旧存储的 username
  const savedPwd = localStorage.getItem('password');

  if (savedAccount && savedPwd) {
    loginForm.account = savedAccount;
    loginForm.password = savedPwd;
    loginForm.remember = true;
  }
});

// 注册弹窗控制（不变）
const isRegisterDialogOpen = ref(false);
const openRegisterDialog = () => {
  isRegisterDialogOpen.value = true;
};
const handleRegisterSuccess = () => {
  isRegisterDialogOpen.value = false;
  ElMessage.success("注册成功，请登录！");
};
</script>

<style scoped lang="scss">
/* 样式不变，保持原有布局 */
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  position: relative;
  padding: 20px;

  .bg-decoration {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle at 20% 30%, rgba(64, 158, 255, 0.1) 0%, transparent 40%),
    radial-gradient(circle at 80% 70%, rgba(64, 158, 255, 0.1) 0%, transparent 40%);
    z-index: 0;
  }

  .login-card {
    width: 100%;
    max-width: 400px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    position: relative;
    z-index: 1;
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-5px);
    }
  }

  .login-header {
    text-align: center;
    padding: 30px 20px 10px;

    .login-title {
      margin: 0 0 10px;
      color: #1d2129;
      font-weight: 600;
      font-size: 24px;
    }

    .login-desc {
      margin: 0;
      color: #86909c;
      font-size: 14px;
    }
  }

  .login-form {
    padding: 20px 30px 30px;

    .remember-me {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .forgot-link {
      font-size: 13px;
    }

    .login-btn {
      width: 100%;
      height: 44px;
      font-size: 16px;
    }
  }

  .login-footer {
    margin-top: 20px;
    color: #86909c;
    font-size: 12px;
    text-align: center;
    position: relative;
    z-index: 1;
  }
}

// 适配移动端
@media (max-width: 576px) {
  .login-card {
    max-width: 100%;
  }

  .login-header {
    padding: 25px 15px 5px;
  }

  .login-form {
    padding: 15px 20px 25px;
  }
}
</style>